<script lang="ts" setup>

import {useUserStore} from "@/stores/user";
import {base64ToFile} from "@/utils/base64Util";
import {IMessage} from "@/components/aw-message/message";

const userStore = useUserStore()
// 确认上传
const handleCrop = (res: { tempFilePath: string }) => {
  // 上传文件
  uni.uploadFile({
    url: '/upload',
    name: 'file',
    filePath: res.tempFilePath,
    timeout: 10000,
    header: {
      'Avatar': userStore.userInfoData!.userID
    },
    success(res) {
      console.log(res)
      // 判断是否上传成功
      const resultData = JSON.parse(res.data)
      if (resultData.code === '1') {
        // 上传成功，可以更新本地store
        uni.hideLoading()
        userStore.userInfoData!.avatarURL = JSON.parse(res.data).data
        IMessage({
          type: 'success',
          showIcon: true,
          content: '头像修改成功',
        })
        return
      }
      uni.$emit('updateAvatarFail')
      IMessage({
        type: 'error',
        showIcon: true,
        content: resultData.message||'头像上传失败,请稍后重试',
        duration:3000,
      })
    },
    fail(err) {
      uni.hideLoading()
      uni.showToast({
        title: '头像上传失败,请稍后重试',
        icon: 'error',
      })
    },
    complete() {
      setTimeout(() =>{
        uni.navigateBack()
      },200)
    }
  })

  // #ifdef H5
/*  const file = base64ToFile(res.tempFilePath, `avatar_${userStore.userInfoData?.userID}.jpg`);
  console.log(file)*/
  // #endif
}
</script>

<template>
  <view>
    <qf-image-cropper
        :src="userStore.userInfoData?.avatarURL"
        fileType="jpg"
        @crop="handleCrop"
    ></qf-image-cropper>
  </view>
</template>


<style lang="scss" scoped>

</style>
